//
//  ZQFileTools.m
//  BuDeJie
//
//  Created by zuqiu on 17/11/17.
//  Copyright © 2017年 zuqiu. All rights reserved.
//  处理文件缓存 

#import "ZQFileTools.h"

@implementation ZQFileTools

+ (void)removeDirectory:(NSString *)directoryPath
{
    
    NSFileManager *mgr = [NSFileManager defaultManager];
    // 是否是文件夹
    BOOL isDirectory;
    // 文件是否存在
    BOOL isExit = [mgr fileExistsAtPath:directoryPath isDirectory:&isDirectory];
    
    if(!isExit || !isDirectory) {
        NSException *exce =  [NSException exceptionWithName:@"pathError" reason:@"这里得传一个文件夹的路径并且路径要存在" userInfo:nil];
        [exce raise];
    }
    // 获取cache文件下的所有文件，不包括子路径的子路径(拿到1级路径)
    NSArray *subPaths =  [mgr contentsOfDirectoryAtPath:directoryPath error:nil];
    for (NSString *subPath in subPaths) {
        NSString *filePath = [directoryPath stringByAppendingPathComponent:subPath];
        [mgr removeItemAtPath:filePath error:nil];
    }
}

+ (void)getFileSize:(NSString *)directoryPath completion:(void(^)(NSInteger))completion
{

    NSFileManager *mgr = [NSFileManager defaultManager];
    // 是否是文件夹
    BOOL isDirectory;
    // 文件是否存在
    BOOL isExit = [mgr fileExistsAtPath:directoryPath isDirectory:&isDirectory];
    
    if(!isExit || !isDirectory) {
     NSException *exce =  [NSException exceptionWithName:@"pathError" reason:@"这里得传一个文件夹的路径并且路径要存在" userInfo:nil];
        [exce raise];
    }
    // 获取文件夹下的所有子路径
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        
    NSArray *subPaths = [mgr subpathsAtPath:directoryPath];
        
    NSInteger totalSize = 0;
    for (NSString *subPath in subPaths) {
        
        NSString   *filePath = [directoryPath stringByAppendingPathComponent:subPath];
        if ([filePath containsString:@".DS"]) continue;
        
        // 是否是文件夹
        BOOL isDirectory;
        // 文件是否存在
        BOOL isExit = [mgr fileExistsAtPath:filePath isDirectory:&isDirectory];
        
        if(!isExit || isDirectory) continue;
        // 获取cache文件下的所有文件，包括子路径的子路径
        NSDictionary *attr = [mgr attributesOfItemAtPath:filePath error:nil];
        NSInteger fileSize = (int)[attr fileSize];
        totalSize += fileSize;
      }
        dispatch_async(dispatch_get_main_queue(), ^{
            if (completion) {
                completion(totalSize);
            }
        });
    });
}

@end
